package handler

import (
	"encoding/json"
	"gin/cache"
	"gin/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	typ := c.PostForm("typ")
	if name == "" || typ == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.Car{
		Name: name,
		Typ:  typ,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func CreateOrder(c *gin.Context) {
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	price, _ := strconv.Atoi(c.PostForm("price"))
	if cid == 0 || price == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.Order{
		Cid:   cid,
		Price: price,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var order []model.CarOrder
	redis_key := "orders_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select("orders.id as  Oid ",
				"cars.`name` as `Name` ",
				"cars.typ as Typ ",
				"orders.cid as Cid  ",
				"orders.price as Price").
			Joins("LEFT JOIN cars ON orders.cid = cars.id").
			Offset(offset).
			Limit(size).
			Find(&order)
		jsonData, _ := json.Marshal(&order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	var total int64
	model.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  order,
		"total": total,
		"page":  page,
	})
}
func OrderDetail(c *gin.Context) {
	cid, _ := strconv.Atoi(c.DefaultQuery("cid", "1"))
	var order model.CarOrder
	redis_key := "orders_" + strconv.Itoa(cid)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select("orders.id as  Oid",
				"cars.`name` as `Name`",
				"cars.typ as Typ",
				"orders.cid as Cid",
				"orders.price as Price").
			Joins("LEFT JOIN cars ON orders.cid = cars.id").
			Where("").
			Limit(1).
			Find(&order)
		jsonData, _ := json.Marshal(&order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": order,
	})
}
